//表示系统当前的操作类型
var type = "";
//link开始结点
var from_node = null;
var from_port = null;
// link结束结点
var to_node = null;
var to_port = null;
// 系统名称
var systemName = null;
//系统类型
var systemType = null;   //-->main/outer/inner
//是否为主系统
var systemMain = null;
//设备类型
var deviceType = null;   //-->设备列表/其他
//subprogram类型
var subprogramType = null;   //-->subprogram列表/其他
// 设备ID 对应于DataBase的ID
var elementId = "";
// 设备名称
//var deviceName = "";
//elementName 
var elementName = null;
//存放所有结点的map（以id作为key）
//端口type
var port = null;
// 端口名称
var protName = null;
//agent类型
var agentType = null; //-->agent(from rhapsody)/other

//当前正在操作结点
var currentView = null;
var debug;
var paperWidth = 1200;
var paperHeight = 800;
var paperOffset = 600;

var isTemplate = false;
////*************************************以上为全局变量*******************************************///
//oldId->newId
var idMap = new Map();
var nodeMap = new Map();
//存放子图与父图之间的映射关系，便于管理
var downMap = new Map();
//存放所有连线的map（以id作为key）
var linkMap = new Map();
var linkValueMap = new Map();
var nameSet = new Map();
var keyWordSet = new Map();
var keywords = new Array("complete","in","out","event","access","dataEvent","port","requires","provides","features","subcomponents","connections","properties","implementation","end","device","system","data","subprogram","thread","process","processor","threadgroup","memory","bus","group","extends","implements");
var _size = keywords.length;
for(var i=0;i<_size;i++){
	nameSet.put(keywords[i],"");
	keyWordSet.put(keywords[i],"");
}
// ////////////////////////////
// 外部系统用的主graph
var graph = new joint.dia.Graph;
// 外部系统用的主paper
var paper = new joint.dia.Paper({
	el : $('#paper'),
	width : paperWidth,
	height : paperHeight,
	gridSize : 1,
	model : graph
});
//paper画布所在div
var paperDiv = $("#paper");
paperDiv.height(paperHeight);
paperDiv.width(paperWidth);

function editDown(){
	goToNormal();
	$("#down_li").addClass("active");
	type = "down";
}

function editBind(){
	goToNormal();
	$("#bind_li").addClass("active");
	type = "bind";
}

var createNode = function(xP, yP, name, image) {
	var node = new joint.shapes.devs.Atomic({
		position : {
			x : xP,
			y : yP
		},
		attrs : {
			image : {
				'xlink:href' : 'img/aadl/' + image
			},
			'.label' : {
				text : name
			},
//			'.name' : {
//				text : name
//			}
		}
	});
	graph.addCell(node);
	nameSet.put(name.toLowerCase(),"");
	return node;
};

var createCoupled = function(xP, yP, name,width,height,inports,outports) {
	var node = new joint.shapes.devs.Coupled({
		position : {
			x : xP,
			y : yP
		},
		attrs : {
			'.label' : {
				text : name
			}
		},
		size : {
			width : width,
			height : height
		},
		inPorts : inports,
		outPorts : outports
	});
	graph.addCell(node);
	return node;
};

// 空白位置点击处理事件
paper.on('blank:pointerdown', function(evt, xP, yP) {
	// alert('pointerdown on a blank area in the paper.'+"x:"+x+"-y:"+y);
	switch (type) {
		case "device":
			if(deviceType == "inner"){
				return;
			}
			// 图中结点
			var node = createNode(xP, yP, elementName, type+'_large.png');
			// 保存的结点
			var value = new Node(node, type, deviceType,null,elementName,null,elementId,false);
			// 压至map
			nodeMap.put(node.id, value);
			goToNormal();
			break;
		case "bus":
		case "memory":
		case "process":
		//case "thread":
		case "data":
		//case "subprogram":
		//case "threadgroup":
		case "processor":
			// 图中结点
			var node = createNode(xP, yP, elementName, type+'_large.png');
			// 保存的结点
			var value = new Node(node, type, null,null,elementName,null,elementId,false);
			// 压至map
			nodeMap.put(node.id, value);
			goToNormal();
			break;
		case "system":
			if(systemType == "inner"){
				return;
			}
			// 图中结点
			var node = createNode(xP, yP, systemName, type+'_large.png');
			// 保存的结点
			var value = new Node(node, type,systemType,null,systemName,null,elementId,false);
			// 压至map
			nodeMap.put(node.id, value);
			goToNormal();
			var cellView = paper.findViewByModel(node);
			if(systemType == "main"){				
				port = "Requires Bus Access";
				name = "outer_bus_in";
				addPortToCell(cellView, name);
//				port = "Provides Bus Access";
//				name = "outer_bus_out";
//				addPortToCell(cellView, name);
			}else if(systemType == "outer"){
				port = "Requires Bus Access";
				name = "bus_in";
				addPortToCell(cellView, name);
//				port = "Provides Bus Access";
//				name = "bus_out";
//				addPortToCell(cellView, name);
			}
			break;
	}

});
// //////////////////////////////////

//清空所有中间变量的值
function refresh() {
	type = "";
	from_node = null;
	from_port = null;
	to_node = null;
	to_port = null;
	systemName = null;
	//systemType = null; //保持惯性
	systemMain = null;
	elementId = "";
	deviceName = "";
	elementName = null;
	port = null;
	protName = null;
	currentView = null;
	isTemplate = false;
	agentType = null;
}
//恢复所有家中色彩的菜单项
function goToNormal() {
	ulgoToNormal("feature_div");
	ulgoToNormal("operation_div");
	ulgoToNormal("type_div");
	$("#port_name").val("");
	$("#element_name").val("");
	$("#property_name").val("");
	$("#property_value").val("");
	refresh();
}
function ulgoToNormal(divName) {
	var name = "#"+divName+" ul li";
	$(name).each(function() {
		$(this).removeClass("active");
	});
}
// 删除元素
function deleteObject() {
	goToNormal();
	$("#delete_li").addClass("active");
	type = "delete";
}
function click_main_system(){
	$("#div_outter_device").hide();
	$("#div_inner_system").hide();	
	$("#div_system_name").toggle("normal");
	systemType = "main";   //-->main/outer
	type = "system";
}
 
function click_inner_system(){
	$("#div_system_name").hide();
	$("#div_outter_device").hide();
	$("#div_inner_system").toggle("normal");
	systemType = "inner";
	type = "system";
}


function addSystem() {
	goToNormal();
	$("#system_li").addClass("active");
	type = "system";
	$("#systemLabel").text('System');
	$("#systemModal").modal({backdrop:false,show:true});
}

function confirmSystemName(){
	if(systemType == "main"){
		$("#help_system_name").text("英文");
		$("#div_system_name").removeClass("control-group error");
		$("#div_system_name").addClass("control-group");
		var name = $("#system_name").val();
		if (name == "" || name == null) {
			$("#div_system_name").removeClass("control-group");
			$("#div_system_name").addClass("control-group error");
			document.getElementById("help_system_name").innerHTML = "名称不能为空";
			return;
		}else if(nameSet.containsKey(name.toLowerCase())) {
			$("#div_system_name").removeClass("control-group");
			$("#div_system_name").addClass("control-group error");
			document.getElementById("help_system_name").innerHTML = "名称与关键字冲突或者重复，请更换";
			return;
		}else{
			var ss = name.split(" ");
			if(ss.length!=1){
				$("#div_system_name").removeClass("control-group");
				$("#div_system_name").addClass("control-group error");
				document.getElementById("help_system_name").innerHTML = "名称中不能包含空格";
				return;
			}else{
				systemName = name;
				$("#system_name").val("");
				$("#systemModal").modal('hide');
				return;
			}
		}
	}else if(systemType == "inner"){
		$("#help_system_name_inner").text("英文");
		$("#div_inner_system_input").removeClass("control-group error");
		$("#div_inner_system_input").addClass("control-group");
		var name = $("#system_name_inner").val();
		if (name == "" || name == null) {
			$("#div_inner_system_input").removeClass("control-group");
			$("#div_inner_system_input").addClass("control-group error");
			document.getElementById("help_system_name_inner").innerHTML = "名称不能为空";
			return;
		}else if(nameSet.containsKey(name.toLowerCase())) {
			$("#div_inner_system_input").removeClass("control-group");
			$("#div_inner_system_input").addClass("control-group error");
			document.getElementById("help_system_name_inner").innerHTML = "名称与关键字冲突或者重复，请更换";
			return;
		}else{
			var ss = name.split(" ");
			if(ss.length!=1){
				$("#div_inner_system_input").removeClass("control-group");
				$("#div_inner_system_input").addClass("control-group error");
				document.getElementById("help_system_name_inner").innerHTML = "名称中不能包含空格";
				return;
			}else{
				systemName = name;			
				if($("#isMainInnerSystem").is(':checked') == true){
					systemMain = "yes";
				}
				$("#system_name_inner").val("");
				$("#systemModal").modal('hide');
				return;
			}
		}
	}
	$("#systemModal").modal('hide');
}

function confirmElementName(){
	$("#help_element_name").text("英文");
	$("#div_element_name").removeClass("control-group error");
	$("#div_element_name").addClass("control-group");
	var name = $("#element_name").val();
	if (name == "" || name == null) {
		$("#div_element_name").removeClass("control-group");
		$("#div_element_name").addClass("control-group error");
		document.getElementById("help_element_name").innerHTML = "名称不能为空";
		return;
	}else if(nameSet.containsKey(name.toLowerCase())) {
		$("#div_element_name").removeClass("control-group");
		$("#div_element_name").addClass("control-group error");
		document.getElementById("help_element_name").innerHTML = "名称与关键字冲突或者重复，请更换";
		return;
	}else{
		var ss = name.split(" ");
		if(ss.length!=1){
			$("#div_element_name").removeClass("control-group");
			$("#div_element_name").addClass("control-group error");
			document.getElementById("help_element_name").innerHTML = "名称中不能包含空格";
			return;
		}else{
			elementName = name;
			$("#elementModal").modal('hide');
		}
	}
}

function addData(){
	goToNormal();
	$("#data_li").addClass("active");
	type = "data";
	$("#elementLabel").text('Data');
	$("#elementModal").modal({backdrop:false,
		show:true});
}
function addSubprogram(){
	goToNormal();
	$("#subprogram_li").addClass("active");
	type = "subprogram";
	//$("#elementLabel").text('Subprogram');
	$("#subprogramModal").modal({backdrop:false,
		show:true});
	agentType = "agent";
	subprogramType = "bus_read";
	document.getElementById("help_subprogram_type").innerHTML = "总线读：";
}
function addThreadGroup(){
	goToNormal();
	$("#threadgroup_li").addClass("active");
	type = "threadgroup";
	$("#elementLabel").text('ThreadGroup');
	$("#elementModal").modal({backdrop:false,
		show:true});
}
//////////添加device///////////////
function addDevice() {
	goToNormal();
	$("#device_li").addClass("active");
	type = "device";
	$("#deviceModal").modal({backdrop:false,
		show:true});
}



function zoomIn(){
	goToNormal();
	$("#zoomin_li").addClass("active");
	type = "zoomin";
}
function zoomOut(){
	goToNormal();
	$("#zoomout_li").addClass("active");
	type = "zoomout";
}

function click_outer_device(){
	$("#div_inner_device_list").hide();
	$("#div_device_else").hide();
	$("#div_outter_device_list").toggle("normal");
	deviceType = "outer";
	type = "device";
}
function click_inner_device(){
	$("#div_outter_device_list").hide();
	$("#div_device_else").hide();
	$("#div_inner_device_list").toggle("normal");
	type = "device";
	deviceType = "inner";
}
function click_device_else(){
	$("#div_inner_device_list").hide();
	$("#div_outter_device_list").hide();
	$("#div_device_else").toggle("normal");
	type = "device";
	deviceType = "else";
}

/*function click_inner_subproram(){
	$("#div_subprogram_else").hide();
	$("#div_inner_subprogram_list").toggle("normal");
	type = "subprogram";
	subprogramType = "inner";
}
function click_else_subprogram(){
	$("#div_inner_subprogram_list").hide();
	$("#div_subprogram_else").toggle("normal");
	type = "subprogram";
	subprogramType = "else";
}*/

function selectDevice() {	
	// //////////device选择处理//////////
	elementName = null;
	if(deviceType  == "inner"){
		$("#device_list tbody tr").each(
				function() {
					if ($(this).children("#td_id").children("#optionsRadios").prop(
							"checked")) {
//						$(this).children("#td_id").children("#optionsRadios").attr(
//								"disabled", true);
						elementId = $(this).children("#td_id").children(
								"#optionsRadios").val();
						elementName = $(this).children("#td_name").text();
					}
				});
		if(elementName != null){
			$("#deviceModal").modal('hide');
		}
	}else if(deviceType == "outer"){	
		$("#outter_device_list tbody tr").each(
				function() {
					if ($(this).children("#td_id").children("#optionsRadios").prop(
							"checked")) {
//						$(this).children("#td_id").children("#optionsRadios").attr(
//								"disabled", true);
						elementId = $(this).children("#td_id").children(
								"#optionsRadios").val();
						elementName = $(this).children("#td_name").text();
					}
					$(this).children("#td_id").children("#optionsRadios").prop(
					"checked");
				});
		if(elementName != null){
			$("#deviceModal").modal('hide');
		}
	}else if(deviceType == "else"){
		$("#help_device_name").text("英文");
		$("#div_device_else").removeClass("control-group error");
		$("#div_device_else").addClass("control-group");
		var name = $("#device_name").val();
		if (name == "" || name == null) {
			$("#div_device_else").removeClass("control-group");
			$("#div_device_else").addClass("control-group error");
			document.getElementById("help_device_name").innerHTML = "名称不能为空";
			return;
		}else{
			var ss = name.split(" ");
			if(ss.length!=1){
				$("#div_device_else").removeClass("control-group");
				$("#div_device_else").addClass("control-group error");
				document.getElementById("help_device_name").innerHTML = "名称中不能包含空格";
				return;
			}else{
				elementName = name;
				$("#device_name").val("");
				$("#deviceModal").modal('hide');
				return;
			}
		}
	}
}
function click_bus_read(){	
	subprogramType = "bus_read";
	document.getElementById("help_subprogram_type").innerHTML = "总线读：";
}
function click_bus_write(){	
	subprogramType = "bus_write";
	document.getElementById("help_subprogram_type").innerHTML = "总线写：";
}
function click_info_display(){	
	subprogramType = "display";
	document.getElementById("help_subprogram_type").innerHTML = "信息显示：";
}
function click_control_react(){	
	subprogramType = "control";
	document.getElementById("help_subprogram_type").innerHTML = "控制响应：";
}

function selectAgentSubprogram(){
	agentType = 'agent';
}

function selectOtherSubprogram(){
	agentType = 'other';
}

function selectSubprogram() {	
	// //////////Subprogram选择处理//////////
	elementName = null;
	if(agentType == 'agent'){
		$("#agent_list tbody tr").each(
				function() {
					if ($(this).children("#td_id").children("#agentOptionsRadios").prop(
							"checked")) {
						elementId = $(this).children("#td_id").children(
								"#agentOptionsRadios").val();
						elementName = $(this).children("#td_name").text();
						subprogramType = $(this).children("#td_type").text();
						if(subprogramType.search("总线通信")>-1){
							subprogramType = "bus";
						}else if(subprogramType.search("控制响应")>-1){
							subprogramType = "control";
						}else if(subprogramType.search("信息显示")>-1){
							subprogramType = "display";
						}
					}
				});
		if(elementName != null){
			$("#subprogramModal").modal('hide');
		}
	}else if(agentType == 'other'){
		$("#help_subprogram_name").text("英文");
		$("#div_subprogram_name").removeClass("control-group error");
		$("#div_subprogram_name").addClass("control-group");
		var name = $("#subprogram_name").val();
		if (name == "" || name == null) {
			$("#subprogram_name").removeClass("control-group");
			$("#subprogram_name").addClass("control-group error");
			document.getElementById("help_subprogram_name").innerHTML = "名称不能为空";
			return;
		}else{
			var ss = name.split(" ");
			if(ss.length!=1){
				$("#div_subprogram_name").removeClass("control-group");
				$("#div_subprogram_name").addClass("control-group error");
				document.getElementById("help_subprogram_name").innerHTML = "名称中不能包含空格";
				return;
			}else{
				elementName = name;
				$("#subprogram_name").val("");
				$("#subprogramModal").modal('hide');
				return;
			}
		}
	}
}
//创建连接--未完成
function addLink() {
	goToNormal();
	$("#link_li").addClass("active");
	type = "link";
}
// 添加bus
function addBus() {
	goToNormal();
	$("#bus_li").addClass("active");
	type = "bus";
	$("#busModal").modal({backdrop:false,
		show:true});
}

function selectBus(){
	////////////bus选择处理//////////
	elementName = null;
	$("#bus_list tbody tr").each(
			function() {
				if ($(this).children("#td_id").children("#optionsRadios").prop(
						"checked")) {
//					$(this).children("#td_id").children("#optionsRadios").attr(
//							"disabled", true);
					elementId = $(this).children("#td_id").children(
							"#optionsRadios").val();
					elementName = $(this).children("#td_name").text();
				}
			});
	if(elementName != null){
		$("#busModal").modal('hide');
	}
}
// 添加进程
function addProcess() {
	goToNormal();
	$("#process_li").addClass("active");
	type = "process";
	$("#elementLabel").text('Process');
	$("#elementModal").modal({backdrop:false,
		show:true});
}

// 添加线程
function addThread() {
	goToNormal();
	$("#thread_li").addClass("active");
	type = "thread";
	$("#elementLabel").text('Thread');
	$("#elementModal").modal({backdrop:false,
		show:true});
}

// 添加memory
function addMemory() {
	goToNormal();
	$("#memory_li").addClass("active");
	type = "memory";
	$("#elementLabel").text('Memory');
	$("#elementModal").modal({backdrop:false,
		show:true});
}
// 添加cpu
function addProcessor() {
	goToNormal();
	$("#processor_li").addClass("active");
	type = "processor";
	$("#elementLabel").text('Processor');
	$("#elementModal").modal({backdrop:false,
		show:true});
}

// 添加port
function addPort() {
	$("#help_port_name").text("英文");
	$("#div_feature_name").removeClass("control-group error");
	$("#div_feature_name").addClass("control-group");

	var name = $("#port_name").val();
	if (name == "" || name == null) {
		$("#div_feature_name").removeClass("control-group");
		$("#div_feature_name").addClass("control-group error");
		document.getElementById("help_port_name").innerHTML = "英文,名称不能为空";
		return;
	}else if(nameSet.containsKey(name.toLowerCase())) {
		$("#div_feature_name").removeClass("control-group");
		$("#div_feature_name").addClass("control-group error");
		document.getElementById("help_port_name").innerHTML = "名称与关键字冲突或者重复，请更换";
		return;
	}else{
		var ss = name.split(" ");
		if(ss.length!=1){
			$("#div_feature_name").removeClass("control-group");
			$("#div_feature_name").addClass("control-group error");
			document.getElementById("help_port_name").innerHTML = "名称中不能包含空格";
			return;
		}else{
			type = "port";
			portName = name;
			$("#portModal").modal('hide');
		}
	}
}
//添加新元素后的事件处理
//graph.on('add', function(cell) {
//});
// /////////////////////////////////
// link source的sourcePort至target的targetPort
var connect = function(source, sourcePort, target, targetPort) {
	var link = null;
	if(sourcePort != null){
		if(targetPort != null){
			link = new joint.shapes.devs.Link({
				source : {
					id : source.id,
					selector : source.getPortSelector(sourcePort)
				},
				target : {
					id : target.id,
					selector : target.getPortSelector(targetPort)
				}
			});
		}else{
				link = new joint.shapes.devs.Link({
					source : {
						id : source.id,
						selector : source.getPortSelector(sourcePort)
					},
					target : {
						id : target.id
					}
				});
		}
	}else{
		if(targetPort != null){
			link = new joint.shapes.devs.Link({
				source : {
					id : source.id
				},
				target : {
					id : target.id,
					selector : target.getPortSelector(targetPort)
				}
			});
		}else{
				link = new joint.shapes.devs.Link({
					source : {
						id : source.id
					},
					target : {
						id : target.id
					}
				});
		}
	}
	graph.addCell(link);
	return link;
};
// link elm1和elm2
var link = function(elm1, elm2) {
	var myLink = new joint.shapes.devs.Line({
		source : {
			id : elm1.id
		},
		target : {
			id : elm2.id
		}
	});
	graph.addCell(myLink);
	return myLink;
};

function checkLinkNode(node){
	if(node != null){ 
//		var nodeType = node.attributes.type;
//		if(nodeType != "devs.Coupled" && nodeMap.get(node.id).getParent() ==null){
//			return false; 
//		}
		return true;
	}
	return false; 
}

// 元素点击事件处理 delete/link
paper.on('cell:pointerup', function(cellView, evt) {
	switch(type){		
		case "link":
			if (from_node == null) {
				from_node = cellView.model;
				if(checkLinkNode(from_node)){
					showPortsToModal(cellView);
					return;
				}else{
					from_node = null;
					document.getElementById("help_tip").innerHTML = "不能为该element添加connection，请重新选择！";
					$("#tipModal").modal({backdrop:false,
						show:true});
					return;
				}
			} else {
				to_node = cellView.model;
				if(checkLinkNode(to_node)){
					var size = showPortsToModal(cellView);
					if(size == 0){
						selectPort();
					}
					return;
				}else{
					to_node = null;
					document.getElementById("help_tip").innerHTML = "不能为该element添加connection，请重新选择！";
					$("#tipModal").modal({backdrop:false,
						show:true});
					return;
				}
			}
			break;
		case  "delete":
			cellView.model.remove();
			goToNormal();
			break;
		case  "port":
			tempNode = nodeMap.get(cellView.model.id);
			if (tempNode.getPorts().get(portName) == null) {
				addPortToCell(cellView, portName);
			} else {
				alert("该名称已被使用，请重新操作");
			}
			goToNormal();
			break;
		case  "edit_features":
			currentView = cellView;
			editPortsToModal(cellView);
			break;
		case "edit_properties":
			currentView = cellView;
			editPropertiesToModal(cellView);
			break;
		case  "down":
			var nodeType = cellView.model.attributes.type;
			if(nodeType != "devs.Coupled"){
				tempNode = nodeMap.get(cellView.model.id);
				var name = tempNode.getName();
				//重新设置高度，添加内嵌图
				paperHeight = paperHeight+paperOffset;
				paper.setDimensions(paperWidth, paperHeight);
				paperDiv.height(paperHeight);
				//用于作为嵌套的cell
				var couple = createCoupled(100, paperHeight - paperOffset, name,750,500,tempNode.getNode().attributes.inPorts,tempNode.getNode().attributes.outPorts);
				// 保存的结点
				var value = new Node(couple, tempNode.getType(),tempNode.getSubType(),tempNode.getIsMian(), name,null,tempNode.getDBId(),true);
				value.setPorts(tempNode.getPorts());
				// 压至map
				nodeMap.put(couple.id, value);
				downMap.put(couple.id,cellView.model.id);
				downMap.put(cellView.model.id,couple.id);
				goToNormal();
			}
			break;
		case "zoomin":
			var nodeType = cellView.model.attributes.type;
			if(nodeType == "devs.Coupled"){
				var height = cellView.model.attributes.size.height;
				var width = cellView.model.attributes.size.width;
				cellView.model.resize(width, height+100);
				paperHeight = paperHeight+100;
				paper.setDimensions(paperWidth, paperHeight);
				paperDiv.height(paperHeight);
				goToNormal();
			}
			break;
		case "zoomout":
			var nodeType = cellView.model.attributes.type;
			if(nodeType == "devs.Coupled"){
				var height = cellView.model.attributes.size.height;
				var width = cellView.model.attributes.size.width;
				if(height>50){
					cellView.model.resize(width, height-100);
				}
				goToNormal();
			}
			break;
		case "bus":
		case "memory":
		case "process":
		case "thread":
		case "data":
		case "subprogram":
		case "threadgroup":
		case "processor":
			var nodeType = cellView.model.attributes.type;
			if(nodeType == "devs.Coupled"){
				// 图中结点
				var node = createNode(cellView.model.attributes.position.x+50, cellView.model.attributes.position.y+50, elementName, type+'_large.png');
				// 保存的结点
				var parentNode = nodeMap.get(cellView.model.id);
				var value = new Node(node, type,null,null,elementName,parentNode,elementId,false);
				// 压至map
				nodeMap.put(node.id, value);
				if(type == "thread"){
					value.addProperty("Dispatch_Protocol", "Periodic");
				}else if(type == "subprogram"){
					value.addProperty("subprogram_type", subprogramType);
					value.addProperty("agent_type", agentType);
				}
				goToNormal();
				cellView.model.embed(node);
			}
			break;
		case "device":
			var nodeType = cellView.model.attributes.type;
			if(nodeType == "devs.Coupled"&& systemType != "outer"){
				// 图中结点
				var node = createNode(cellView.model.attributes.position.x+50, cellView.model.attributes.position.y+50, elementName, type+'_large.png');
				// 保存的结点
				var parentNode = nodeMap.get(cellView.model.id);
				var value = new Node(node, type,deviceType,null,elementName,parentNode,elementId,false);
				// 压至map
				nodeMap.put(node.id, value);
				goToNormal();
				cellView.model.embed(node);
			}
			break;
		case "system":
			var nodeType = cellView.model.attributes.type;
			if(nodeType == "devs.Coupled"&& systemType == "inner"){
				// 图中结点
				var node = createNode(cellView.model.attributes.position.x+50, cellView.model.attributes.position.y+50, systemName, type+'_large.png');
				// 保存的结点
				var parentNode = nodeMap.get(cellView.model.id);
				var value = new Node(node, type, systemType,systemMain,systemName,parentNode,elementId,false);
				// 压至map
				nodeMap.put(node.id, value);
				goToNormal();
				cellView.model.embed(node);
			}
			break;
		case "bind":
			var bind_system_node = cellView.model;
			if(nodeMap.get(bind_system_node.id).getType() == "system"){
				currentView = cellView;
				$("#bindModal").modal({backdrop:false,
					show:true});
			};
			break;
	} 
	
});
function saveBind(){
	$("#help_processor_name").text("");
	$("#div_bind_processor").removeClass("control-group error");
	$("#div_bind_processor").addClass("control-group");

	var name = $("#processor_name").val();
	if (name == "" || name == null) {
		$("#div_bind_processor").removeClass("control-group");
		$("#div_bind_processor").addClass("control-group error");
		document.getElementById("help_processor_name").innerHTML = "名称不能为空";
		return;
	}else if(!nameSet.containsKey(name.toLowerCase())) {
		$("#div_bind_processor").removeClass("control-group");
		$("#div_bind_processor").addClass("control-group error");
		document.getElementById("help_processor_name").innerHTML = "请输入正确的processor名称";
		return;
	}else{
		var ss = name.split(" ");
		if(ss.length!=1){
			$("#div_bind_processor").removeClass("control-group");
			$("#div_bind_processor").addClass("control-group error");
			document.getElementById("help_processor_name").innerHTML = "名称中不能包含空格";
			return;
		}else{			
			//var storeNode = nodeMap.get(currentView.model.id);
			//add to store
			addPropertyToNode("Allowed_Processor_Binding","reference "+name);
			//storeNode.addProperty("Allowed_Processor_Binding","reference "+name);
			goToNormal();
			$("#bindModal").modal('hide');
		}
	}
}

function showPortsToModal(cellView){
	var storeNode = nodeMap.get(cellView.model.id);
	var ports = storeNode.getPorts();
	if(ports.size()>0){
		var keys = ports.keys();
		$("#port_list tbody").html("");
		var rows = $("<tbody></tbody>");
		var size = ports.size();
		for (var i=0;i<=size-1;i++) 
		{   var key = keys[i];
			var value = ports.get(key);
			var tr = $("<tr></tr>");
			var selectTd = $(
					"<td id='td_key'></td>")
					.append(
							"<input type='radio' id='port_key' name='port_key' value='"
+ key + "'>");
			var nameTd = $("<td></td>")
					.append(key);
			var typeTd = $("<td id='td_type'></td>")
					.append(value);
			tr.append(selectTd).append(nameTd)
					.append(typeTd)
					.appendTo(rows);
		}
		$("#port_list tbody").html(rows.html());
		$("#selectModal").modal({backdrop:false,
			show:true});
		return 1;
	}
	return 0;
}


function deltr(delbtn) {	
		/////delete from view//////////
		var tr = $(delbtn).parent("#td_delete").parent("#tr_delete");
		var port = tr.children("#td_key").text();
		var type = tr.children("#td_type").text();
		var name = getPortTypePre(type) + port;
		var result = false;
		//searching from inport
		var inports = currentView.model.attributes.inPorts;
		var size = inports.length;
		for(var i=0;i<size;i++){
			if(inports[i] == name){
				inports.splice(i,1);
				result = true;
				break;
			}
		}
		if(result){
			currentView.addInPorts(currentView.model, inports);
			var cellType = currentView.model.attributes.type;
			if(cellType != "devs.Coupled"){
				resize(currentView,"left");
			}
			var downId = downMap.get(currentView.model.id);
			if(downId != null){
				var downNode = nodeMap.get(downId);
				if(downNode != null){
					var downView = paper.findViewByModel(downNode.getNode());
					var downports = downView.model.attributes.inPorts;	
					var d_size = downports.length;
					for(var i=0;i<d_size;i++){
						if(downports[i] == name){
							downports.splice(i,1);
							break;
						}
					}
					downView.addInPorts(downNode.getNode(), downports);
					var downType = downView.model.attributes.type;
					if(downType != "devs.Coupled"){
						resize(downView,"left");
					}
				}
			}
		}
		//go on searching from outport
		var outports = currentView.model.attributes.outPorts;
		size = outports.length;
		for(var i=0;i<size;i++){
			if(outports[i] == name){
				outports.splice(i,1);
				result = true;
				break;
			}
		}
		if(result){
			currentView.addOutPorts(currentView.model, outports);
			var cellType = currentView.model.attributes.type;
			if(cellType != "devs.Coupled"){
				resize(currentView,"right");
			}
			var downId = downMap.get(currentView.model.id);
			if(downId != null){
				var downNode = nodeMap.get(downId);
				if(downNode != null){
					var downView = paper.findViewByModel(downNode.getNode());
					var downports = downView.model.attributes.outPorts;	
					var d_size = downports.length;
					for(var i=0;i<d_size;i++){
						if(downports[i] == name){
							downports.splice(i,1);
							break;
						}
					}
					downView.addOutPorts(downNode.getNode(), downports);
					var downType = downView.model.attributes.type;
					if(downType != "devs.Coupled"){
						resize(downView,"right");
					}
				}
			}
		}
		///////////delete from store///////////
		$(delbtn).parent("#td_delete").parent("#tr_delete").remove();
		var key = $(delbtn).val();
		var storeNode = nodeMap.get(currentView.model.id);
		storeNode.deletePort(key);
}

function editPortsToModal(cellView){
	var storeNode = nodeMap.get(cellView.model.id);
	var ports = storeNode.getPorts();
	$("#portModalLabel").text("编辑Features");
	if(ports.size()>0){
		var keys = ports.keys();
		$("#port_list tbody").html("");
		var rows = $("<tbody></tbody>");
		var size = ports.size();
		for (var i=0;i<=size-1;i++) 
		{   var key = keys[i];
			var value = ports.get(key);
			var tr = $("<tr id='tr_delete'></tr>");
			var selectTd = $(
					"<td id='td_delete'></td>")
					.append("<button type='button' class='btn btn-warning' onclick='deltr(this)' value='"
+ key + "'>删除</>");
			var nameTd = $("<td id='td_key'></td>")
					.append(key);
			var typeTd = $("<td id='td_type'></td>")
					.append(value);
			tr.append(selectTd).append(nameTd)
					.append(typeTd)
					.appendTo(rows);
		}
		$("#port_list tbody").html(rows.html());
		$("#selectModal").modal({backdrop:false,
			show:true});
		return 1;
	}
	return 0;
}

function delPorperty(delbtn) {
		$(delbtn).parent("#td_delete").parent("#tr_delete").remove();
		var key = $(delbtn).val();
		var storeNode = nodeMap.get(currentView.model.id);
		storeNode.deleteProperty(key);
		var downId = downMap.get(currentView.model.id);
		if(downId != null){
			var downNode = nodeMap.get(downId);
			if(downNode != null){
				downNode.deleteProperty(key);
			}
		}
}

function editPropertiesToModal(cellView){
	currentView = cellView;
	var storeNode = nodeMap.get(cellView.model.id);
	var properties = storeNode.getProperties();
	if(properties.size()>0){
		$("#help_property_name").text("英文");
		$("#div_property_name").removeClass("control-group error");
		$("#div_property_name").addClass("control-group");
		var keys = properties.keys();
		$("#property_list tbody").html("");
		var rows = $("<tbody></tbody>");
		var size = properties.size();
		for (var i=0;i<=size-1;i++) 
		{   var key = keys[i];
			var value = properties.get(key);
			var tr = $("<tr id='tr_delete'></tr>");
			var selectTd = $(
					"<td id='td_delete'></td>")
					.append("<button type='button' class='btn btn-warning' onclick='delPorperty(this)' value='"
+ key + "'>删除</>");
			var nameTd = $("<td id='td_key'></td>")
					.append(key);
			var typeTd = $("<td id='td_type'></td>")
					.append(value);
			tr.append(selectTd).append(nameTd)
					.append(typeTd)
					.appendTo(rows);
		}
		$("#property_list tbody").html(rows.html());
	}
	$("#propertyModal").modal({backdrop:false,
		show:true});
	return 0;
}

function saveProperty(){
	$("#properties_li").removeClass("active");
	goToNormal();
	$("#propertyModal").modal('hide');
	$("#property_list tbody").html("");
}

function addProperty(){
	$("#help_property_name").text("英文");
	$("#div_property_name").removeClass("control-group error");
	$("#div_property_name").addClass("control-group");
	var storeNode = nodeMap.get(currentView.model.id);
	var name = $("#property_name").val();
	if (name == "" || name == null) {
		$("#div_property_name").removeClass("control-group");
		$("#div_property_name").addClass("control-group error");
		document.getElementById("help_property_name").innerHTML = "名称不能为空";
		return;
	}else if(keyWordSet.containsKey(name.toLowerCase())||storeNode.getProperties().get(name) != null) {
		$("#div_property_name").removeClass("control-group");
		$("#div_property_name").addClass("control-group error");
		document.getElementById("help_property_name").innerHTML = "名称与关键字冲突或者重复，请更换";
		return;
	}
	var value = $("#property_value").val();
	if (value == "" || value == null) {
		$("#div_property_name").removeClass("control-group");
		$("#div_property_name").addClass("control-group error");
		document.getElementById("help_property_name").innerHTML = "值不能为空";
		return;
	}
	//add to store
	//storeNode.addProperty(name,value);
	addPropertyToNode(name,value);
	//add to table
	var rows = $("#property_list tbody");
	var tr = $("<tr id='tr_delete'></tr>");
	var selectTd = $(
				"<td id='td_delete'></td>")
				.append("<button type='button' class='btn btn-warning' onclick='delPorperty(this)' value='"
+ name + "'>删除</>");
	var nameTd = $("<td id='td_key'></td>")
				.append(name);
	var typeTd = $("<td id='td_type'></td>")
				.append(value);
	tr.append(selectTd).append(nameTd)
				.append(typeTd)
				.appendTo(rows);
	//back to normal
	$("#help_property_name").text("英文");
	$("#property_name").val("");
	$("#property_value").val("");
}

function addPropertyToNode(name,value){
	var tempNode = nodeMap.get(currentView.model.id);
	tempNode.addProperty(name,value);
	var downId = downMap.get(currentView.model.id);
	if(downId != null){
		var downNode = nodeMap.get(downId);
		if(downNode != null){
			downNode.addProperty(name,value);
		}
	}
}
function getPortTypePre(type) {
	switch (type) {
	case "In Data Port":
		return "In Data:";
	case "Out Data Port":
		return "Out Data:";
	case "InOut Data Port":
		return "InOut Data:";
	case "In Event Port":
		return "In Event:";
	case "Out Event Port":
		return "Out Event:";
	case "InOut Event Port":
		return "InOut Event:";
	case "In DataEvent Port":
		return "In DataEvent:";
	case "Out DataEvent Port":
		return "Out DataEvent:";
	case "InOut DataEvent Port":
		return "InOut DataEvent:";
	case "Requires Data Access":
		return "Requires Data:";
	case "Provides Data Access":
		return "Provides Data:";
	case "Requires Bus Access":
		return "Requires Bus:";
	case "Provides Bus Access":
		return "Provides Bus:";
	}
}
function linkToValue(sourceId,sourcePort,targetId,targetPort){
	if(sourceId>targetId){
		return ""+sourceId +":" +sourcePort +"-"+targetId +":"+targetPort;
	}else{
		return ""+targetId +":"+targetPort+"-"+sourceId +":" +sourcePort;
	}
}


// 根据具体的port类型，添加至cellView
function addPortToCell(cellView, name) {
	switch (port) {
	case "In Data Port":
	case "In Event Port":
	case "InOut Data Port":
	case "InOut Event Port":
	case "In DataEvent Port":
	case "InOut DataEvent Port":
	case "Requires Data Access":
	case "Requires Bus Access":
		var nodeType = cellView.model.attributes.type;
		if(nodeType != "devs.Coupled"){
			resize(cellView,"left");
		}
		
		inports = cellView.model.attributes.inPorts;
		inports.push(getPortTypePre(port)+name);	
		cellView.addInPorts(cellView.model, inports);
		tempNode = nodeMap.get(cellView.model.id);
		tempNode.addPort(name, port);
		
		var downId = downMap.get(cellView.model.id);
		if(downId != null){
			var downNode = nodeMap.get(downId);
			if(downNode != null){
				var downView = paper.findViewByModel(downNode.getNode());
				var downType = downView.model.attributes.type;
				if(downType != "devs.Coupled"){
					resize(downView,"left");
				}
				var downports = downView.model.attributes.inPorts;
				downports.push(getPortTypePre(port)+name);
				downView.addInPorts(downNode.getNode(), downports);
			}
		}
		break;
	case "Out Data Port":
	case "Out Event Port":
	case "Out DataEvent Port":
	case "Provides Data Access":
	case "Provides Bus Access":
		var nodeType = cellView.model.attributes.type;
		if(nodeType != "devs.Coupled"){
			resize(cellView,"right");
		}
		outports = cellView.model.attributes.outPorts;
		outports.push(getPortTypePre(port)+name);
		cellView.addOutPorts(cellView.model, outports);
		tempNode = nodeMap.get(cellView.model.id);
		tempNode.addPort(name, port);
		
		var downId = downMap.get(cellView.model.id);
		if(downId != null){
			var downNode = nodeMap.get(downId);
			if(downNode != null){	
				var downView = paper.findViewByModel(downNode.getNode());
				var downType = downView.model.attributes.type;
				if(downType != "devs.Coupled"){
					resize(downView,"right");
				}
				var downports = downView.model.attributes.outPorts;
				downports.push(getPortTypePre(port)+name);
				downView.addOutPorts(downNode.getNode(), downports);
			}
		}
		break;
	}
}

function resize(cellView,direction){
	switch(direction){
	case "left":
		var inports = cellView.model.attributes.inPorts;
		if(inports.length <2){
			return;
		}else if(inports.length < 4){
			cellView.model.resize(150, 150);
		}else if(inports.length < 6){
			cellView.model.resize(200, 200);
		}else{
			var offset = inports.length-6;
			cellView.model.resize(200+offset*15, 200+offset*15);
		}
	case "right":
		var outports = cellView.model.attributes.outPorts;
		if(outports.length <2){
			return;
		}else if(outports.length < 4){
			cellView.model.resize(150, 150);
		}else if(outports.length < 6){
			cellView.model.resize(200, 200);
		}else{
			var offset = outports.length-6;
			cellView.model.resize(200+offset*15, 200+offset*15);
		}
	case "top":
	case "bottom":
	}
	
}

function editFeatures(){
	goToNormal();
	$("#features_li").addClass("active");
	type = "edit_features";
}

function editProperty(){
	goToNormal();
	$("#properties_li").addClass("active");
	type = "edit_properties";
}

function checkLinkPort(from_port,from_node,to_port,to_node){
	if(nodeMap.get(from_node.id).getParent() != null && nodeMap.get(from_node.id).getParent().getNode()== to_node){
		return true;
	}
	if(nodeMap.get(to_node.id).getParent() != null && nodeMap.get(to_node.id).getParent().getNode() == from_node){
		return true;
	}
	if(from_port != null){
		if(from_port.match("Out")||from_port.match("InOut")||from_port.match("Provides")){
			if(to_port == null){
				if(nodeMap.get(to_node.id).getType() == "bus"){
					if(from_port.match("Provides Bus")||from_port.match("Requires Bus")){
						return true;
					}
					return false;
				}else if(nodeMap.get(to_node.id).getType() == "data" ){
					if(from_port.match("Provides Data")||from_port.match("Requires Data")){
						return true;
					}
					return false;
				}else{
					return false;
				}
			}else{
				if(from_port.match("InOut Data:")||from_port.match("Out Data:")){
					if(to_port.match("InOut Data:")||to_port.match("In Data:")){
						return true;
					}else{
						return false;
					}
				}
				if(from_port.match("InOut Event")||from_port.match("Out Event")){
					if(to_port.match("InOut Event")||to_port.match("In Event")){
						return true;
					}else{
						return false;
					}
				}
				if(from_port.match("InOut DataEvent")||from_port.match("Out DataEvent")){
					if(to_port.match("InOut DataEvent")||to_port.match("In DataEvent")){
						return true;
					}else{
						return false;
					}
				}
				if(from_port.match("Provides Data") &&to_port.match("Requires Data")){
						return true;
				}
				if(from_port.match("Provides Bus")&&to_port.match("Requires Bus")){
						return true;
				}
				return false;
			}
		}else{
			return false;
		}
	}else{
		if(nodeMap.get(from_node.id).getType() == "bus"){
			if(to_port != null &&(to_port.match("Requires Bus")||to_port.match("Provides Bus"))){
				return true;
			}
			return false;
		}else if(nodeMap.get(from_node.id).getType() == "data" ){
			if(to_port != null&&(to_port.match("Requires Data")||to_port.match("Provides Data"))){
				return true;
			}
			return false;
		}else{
			return false;
		}
	}
}

function selectPort(){
	if(type == "edit_features"){
		goToNormal();
		$("#selectModal").modal('hide');
		$("#port_list tbody").html("");
		return;
	}
	var size = $("#port_list tbody tr").length;
	if(size>0){
		$("#port_list tbody tr").each(function() {
			if ($(this).children("#td_key")
					.children("#port_key").prop("checked")) {
				var temp = $(this).children("#td_type")
				.text();
				if(to_node == null){
					from_port = getPortTypePre(temp) + $(this).children("#td_key")
					.children("#port_key").val();
				}else{
					to_port = getPortTypePre(temp) + $(this).children("#td_key")
					.children("#port_key").val();
				}
				$("#selectModal").modal('hide');
				$("#port_list tbody").html("");
				return;
			}
		});
	}

	
	if(to_node != null){
		var temp = linkToValue(from_node.id, from_port ,to_node.id, to_port);
		if(linkValueMap.get(temp) == null){
			if(checkLinkPort(from_port,from_node,to_port,to_node)){
				var myLink = connect(from_node, from_port, to_node, to_port);
				var value = new Connect(type, from_node.id, from_port ,to_node.id, to_port);
				linkMap.put(myLink.id, value);
				linkValueMap.put(value.toValue(),"");
			}else{
				document.getElementById("help_tip").innerHTML = "connection不符合要求，请重新添加！";
				$("#tipModal").modal({backdrop:false,
					show:true});
			}
		}
		from_node = null;
		to_node = null;
		from_port = null;
		to_port = null;
		goToNormal();
	}
}
//删除连线以及node的处理
graph.on('remove', function(cell) {
	// 对于connect的删除处理
	var temp = linkMap.get(cell.id);
	if (temp != null) {
		linkMap.remove(cell.id);
		linkValueMap.remove(temp.toValue());
	}
	// 对于Node的删除处理
	var tempNode = nodeMap.get(cell.id);
	if (tempNode != null) {
		nodeMap.remove(cell.id);
		nameSet.remove(tempNode.getName().toLowerCase());
	}
});
//添加port的裁断点击处理
$("#feature_div ul li a").on('click', function() {
	goToNormal();
	$(this).parent().addClass("active");
	type = "port";
	port = $(this).children("#port").text();
	$("#portModal").modal({backdrop:false,
		show:true});
});
//////////////////////提交aadl图///////////////////////
function getAADLXML(){
	var xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><content height=\""+paperHeight+"\" width=\""+paperWidth+"\">";
	var size = nodeMap.size();
	if(size > 0 ){
		var keys = nodeMap.keys();
		for (var i=0;i<=size-1;i++) 
		{
			var key = keys[i];
			var value = nodeMap.get(key);
			xml += value.toXml();
		}
	}
	size = linkMap.size();
	if(size > 0 ){
		var keys = linkMap.keys();
		for (var i=0;i<=size-1;i++) 
		{
			var key = keys[i];
			var value = linkMap.get(key);
			xml += value.toXml();
		}
	}
	return xml+"</content>";
}

function submitAADLModelUpdate(projectId,opertype,uri){
	var logerInfo = $("#loger_info").val();
	$("#div_model_loger").addClass("control-group");
	$("#div_model_loger").removeClass("control-group error");
	if (logerInfo == "" || logerInfo == null) {
		$("#div_model_loger").removeClass("control-group");
		$("#div_model_loger").addClass("control-group error");
		return;
	}
	
	var submitForm = document.createElement("form");
	document.body.appendChild(submitForm);
	submitForm.method = "POST";
	var newElement = document.createElement("input");
    newElement.setAttribute("name","aadl_xml");
    newElement.setAttribute("type","hidden");
    newElement.setAttribute("value",getAADLXML());
    submitForm.appendChild(newElement);
    var projectIdElement = document.createElement("input");
    projectIdElement.setAttribute("name","projectId");
    projectIdElement.setAttribute("type","hidden");
    projectIdElement.setAttribute("value",projectId);
    submitForm.appendChild(projectIdElement);
    
    var logerElement = document.createElement("input");
    logerElement.setAttribute("name","logerInfo");
    logerElement.setAttribute("type","hidden");
    logerElement.setAttribute("value",logerInfo);
    submitForm.appendChild(logerElement);
    
    submitForm.action = "aadl/model/"+uri+"/update";
    submitForm.submit();
	return;
}

function submitAADL(projectId,opertype,uri,tempName,tempDes,groupid){
	//实例
	if(projectId != '0' && projectId != 'null' && projectId != null){
		if(opertype == 'update'){
			$("#logerModal").modal({backdrop:false,
				show:true});
		    return;
		}
	}
	$("#div_template_radio").show();
	$("#div_template_info").show();
	$("#templateModal").modal({backdrop:false,
		show:true});
	if(projectId == '0' ||projectId == 'null'||projectId == null){
		$("#div_template_radio").hide();
		isTemplate = true;
		$("#template_name").val(tempName);
		$("#template_description").val(tempDes);
		$(".selector").val(groupid);
		if(opertype == 'update'){
			$("#div_template_loger").show();
		}else{
			$("#div_template_loger").hide();
		}
	}else{
		//$("#div_template_info").hide();
		submitAADLTemplate(projectId,opertype,uri);
	}
}
function click_template_yes(){
	$("#div_template_info").show();
	isTemplate = true;
}

function click_template_no(){
	$("#div_template_info").hide();
	isTemplate = false;
}
//提交aadl实例或者模板
function submitAADLTemplate(projectId,opertype,uri){
	if(isTemplate){
		var template_name = $("#template_name").val();
		var template_description = $("#template_description").val();
		
		var groupid =  $("#groupid").val();
		$("#div_template_name").removeClass("control-group error");
		$("#div_template_name").addClass("control-group");
		if (template_name == "" || template_name == null) {
			$("#div_template_name").removeClass("control-group");
			$("#div_template_name").addClass("control-group error");
			return;
		}
		var logerInfo = $("#template_loger_info").val();
		if(opertype == 'update'){
			$("#div_template_loger").addClass("control-group");
			$("#div_template_loger").removeClass("control-group error");
			if (logerInfo == "" || logerInfo == null) {
				$("#div_template_loger").removeClass("control-group");
				$("#div_template_loger").addClass("control-group error");
				return;
			}
		}
		
		$("#templateModal").modal('hide');
		var submitForm = document.createElement("form");
		document.body.appendChild(submitForm);
		submitForm.method = "POST";
		var newElement = document.createElement("input");
	    newElement.setAttribute("name","aadl_xml");
	    newElement.setAttribute("type","hidden");
	    newElement.setAttribute("value",getAADLXML());
	    submitForm.appendChild(newElement);
	    var nameElement = document.createElement("input");
	    nameElement.setAttribute("name","name");
	    nameElement.setAttribute("type","hidden");
	    nameElement.setAttribute("value",template_name);
	    submitForm.appendChild(nameElement);
	    var desElement = document.createElement("input");
	    desElement.setAttribute("name","description");
	    desElement.setAttribute("type","hidden");
	    desElement.setAttribute("value",template_description);
	    submitForm.appendChild(desElement);
	    
	    var groupElement = document.createElement("input");
	    groupElement.setAttribute("name","groupid");
	    groupElement.setAttribute("type","hidden");
	    groupElement.setAttribute("value",groupid);
	    submitForm.appendChild(groupElement);
	    
	    var projectIdElement = document.createElement("input");
	    projectIdElement.setAttribute("name","projectId");
	    projectIdElement.setAttribute("type","hidden");
	    projectIdElement.setAttribute("value",projectId);
	    submitForm.appendChild(projectIdElement);
	    
	    if(opertype == 'update'){
	    	var logerElement = document.createElement("input");
		    logerElement.setAttribute("name","logerInfo");
		    logerElement.setAttribute("type","hidden");
		    logerElement.setAttribute("value",logerInfo);
		    submitForm.appendChild(logerElement);
	    	submitForm.action = "aadl/template/"+uri+"/update";
	    }else{
	    	submitForm.action = "aadl/template/edit";
	    }
	    submitForm.submit();
	}else{
		$("#templateModal").modal('hide');
		var submitForm = document.createElement("form");
		document.body.appendChild(submitForm);
		submitForm.method = "POST";
		var newElement = document.createElement("input");
	    newElement.setAttribute("name","aadl_xml");
	    newElement.setAttribute("type","hidden");
	    newElement.setAttribute("value",getAADLXML());
	    submitForm.appendChild(newElement);
	    var projectIdElement = document.createElement("input");
	    projectIdElement.setAttribute("name","projectId");
	    projectIdElement.setAttribute("type","hidden");
	    projectIdElement.setAttribute("value",projectId);
	    submitForm.appendChild(projectIdElement);
	    
	    submitForm.action = "aadl/model/edit";
	    submitForm.submit();
	}
	
}
////////////////////////////////////以下为update用函数////////////////////////
var createNodeFromJson = function(xP, yP,height,width, name, image,inports,outports) {
	var node = new joint.shapes.devs.Atomic({
		position : {
			x : xP,
			y : yP
		},
		size : {
			width : width,
			height : height
		},
		attrs : {
			image : {
				'xlink:href' : 'img/aadl/' + image
			},
			'.label' : {
				text : name
			}
		},
		inPorts : inports,
		outPorts : outports
	});
	graph.addCell(node);
	nameSet.put(name.toLowerCase(),"");
	return node;
};

var createCoupledFromJson = function(xP, yP, name,width,height,inports,outports) {
	var node = new joint.shapes.devs.Coupled({
		position : {
			x : xP,
			y : yP
		},
		attrs : {
			'.label' : {
				text : name
			}
		},
		size : {
			width : width,
			height : height
		},
		inPorts : inports,
		outPorts : outports
	});
	graph.addCell(node);
	return node;
};

function getPortTypeDirection(type) {
	switch (type) {
	case "In Data Port":
	case "InOut Data Port":
	case "In Event Port":
	case "InOut Event Port":
	case "In DataEvent Port":
	case "InOut DataEvent Port":
	case "Requires Data Access":
	case "Requires Bus Access":
		return "in";
	case "Out Data Port":
	case "Out Event Port":
	case "Out DataEvent Port":
	case "Provides Data Access":
	case "Provides Bus Access":
		return "out";
	}
}
function parseNode(nodeJson){
	var size = nodeJson.length;
	for(var i= 0;i<size;i++){
		var inports = new Array();
		var outports = new Array();
		var ports = new Map();
		var properties = new Map();
		if(nodeJson[i].features != null&&nodeJson[i].features != "null"){
			var port_size = nodeJson[i].features.length;
			for(var j=0;j<port_size;j++){
				var name = nodeJson[i].features[j].name;
				var type = parseFeatureType(nodeJson[i].features[j].type);
				var port = getPortTypePre(type)+name;
				ports.put(name,type);
				var direction = getPortTypeDirection(type);
				if(direction == "in"){
					inports.push(port);
				}else{
					outports.push(port);
				}
			}
		}
		if(nodeJson[i].properties != null &&nodeJson[i].properties != "null"){
			var prop_size = nodeJson[i].properties.length;
			for(var j=0;j<prop_size;j++){
				var name = nodeJson[i].properties[j].name;
				var value = nodeJson[i].properties[j].value;
				properties.put(name,value);
			}
		}
		if(!nodeJson[i].hasChild){
			var node = createNodeFromJson(nodeJson[i].x, nodeJson[i].y,nodeJson[i].height,nodeJson[i].width, nodeJson[i].name, nodeJson[i].type+"_large.png",inports,outports);
			// 保存的结点
			var db_id = nodeJson[i].db_id=="null"?null:nodeJson[i].db_id;
			var subtype = nodeJson[i].subtype=="null"?null:nodeJson[i].subtype;
			var isMain = nodeJson[i].isMain=="null"?null:nodeJson[i].isMain;
			//尚未设置parent
			var value = new Node(node, nodeJson[i].type,subtype,isMain, nodeJson[i].name,null,db_id,false);
			value.setPorts(ports);
			value.setProperties(properties);
			// 压至map
			nodeMap.put(node.id, value);
			idMap.put(nodeJson[i].id,node.id);
		}else{
			//重新设置高度，添加内嵌图
			paperHeight = paperHeight+paperOffset;
			paper.setDimensions(paperWidth, paperHeight);
			paperDiv.height(paperHeight);
			var node = createCoupledFromJson(nodeJson[i].x, nodeJson[i].y, nodeJson[i].name,nodeJson[i].width,nodeJson[i].height,inports,outports);
			// 保存的结点
			var db_id = nodeJson[i].db_id=="null"?null:nodeJson[i].db_id;
			var subtype = nodeJson[i].subtype=="null"?null:nodeJson[i].subtype;
			var isMain = nodeJson[i].isMain=="null"?null:nodeJson[i].isMain;
			//尚未设置parent
			var value = new Node(node, nodeJson[i].type,subtype,isMain, nodeJson[i].name,null,db_id,true);
			value.setPorts(ports);
			value.setProperties(properties);
			// 压至map
			nodeMap.put(node.id, value);		
			idMap.put(nodeJson[i].id,node.id);
		}
		
	}
	for(var i= 0;i<size;i++){
		var parent_id = nodeJson[i].db_id=="null"?null:nodeJson[i].parent_id;
		if(parent_id != null){
			var parent = nodeMap.get(idMap.get(parent_id));
			nodeMap.get(idMap.get(nodeJson[i].id)).setParent(parent);
		}
	}
	
}

function parseFeatureType(aadlType){
	switch(aadlType){
		case"in data port":
			return "In Data Port";
		case "out data port":
			return "Out Data Port";
		case "in out data port":
			return "InOut Data Port";
		case "in event port":
		return "In Event Port";
		case "out event port":
			return "Out Event Port";
		case "in out event port":
			return "InOut Event Port";
		case "in event data port":
			return "In DataEvent Port";
		case "out event data port":
			return "Out DataEvent Port";
		case "in out event data port":
			return "InOut DataEvent Port";
		case "requires data access":
			return "Requires Data Access";
		case "provides data access":
			return "Provides Data Access";
		case "requires bus access":
			return "Requires Bus Access";
		case "provides bus access":
			return "Provides Bus Access";
	}
	return "";
}

function parseLink(linkJson){
	var size = linkJson.length;
	for(var i= 0;i<size;i++){
		var sourceId = linkJson[i].sourceId;
		var sourcePort = linkJson[i].sourcePort=="null"?null:linkJson[i].sourcePort;
		var targetId = linkJson[i].targetId;
		var targetPort = linkJson[i].targetPort=="null"?null:linkJson[i].targetPort;
		
		var temp = linkToValue(nodeMap.get(idMap.get(sourceId)).getNode().id, sourcePort ,nodeMap.get(idMap.get(targetId)).getNode().id, targetPort);
		if(linkValueMap.get(temp) == null){
			var myLink = connect(nodeMap.get(idMap.get(sourceId)).getNode(), sourcePort, nodeMap.get(idMap.get(targetId)).getNode(), targetPort);
			var value = new Connect(linkJson[i].type, nodeMap.get(idMap.get(sourceId)).getNode().id, sourcePort ,nodeMap.get(idMap.get(targetId)).getNode().id, targetPort);
			linkMap.put(myLink.id, value);
			linkValueMap.put(value.toValue(),"");
		}
	}
}